﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace ColorPicker
{
    public class CPTool
    {


        /// 获取指定窗口的设备场景
        /// 将获取其设备场景的窗口的句柄。若为0，则要获取整个屏幕的DC
        /// 指定窗口的设备场景句柄，出错则为0
        [DllImport("user32.dll")]
        public static extern IntPtr GetDC(IntPtr hwnd);


        ///
        /// 释放由调用GetDC函数获取的指定设备场景
        ///
        /// 要释放的设备场景相关的窗口句柄
        /// 要释放的设备场景句柄
        /// 执行成功为1，否则为0
        [DllImport("user32.dll")]
        public static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);


        ///
        /// 在指定的设备场景中取得一个像素的RGB值
        ///
        /// 一个设备场景的句柄
        /// 逻辑坐标中要检查的横坐标
        /// 逻辑坐标中要检查的纵坐标
        /// 指定点的颜色
        [DllImport("gdi32.dll")]
        public static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

        /// <summary>
        ///  获取指定屏幕位置的像素点
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static Color GetArgb(int x, int y)
        {
            IntPtr hdc = GetDC(IntPtr.Zero);
            uint pixel = GetPixel(hdc, x, y);
            ReleaseDC(IntPtr.Zero, hdc);
            int r = (int)(pixel & 0xFF);//转换R 
            int g = (int)(pixel & 0xFF00) / 256;//转换G 
            int b = (int)(pixel & 0xFF0000) / 65536;//转换B 
            return Color.FromArgb(r, g, b);
        }

        /// <summary>
        ///  获取16进制的颜色值
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static string GetColorHexHtml(int x, int y)
        {

            Color c = GetArgb(x, y);
            return ColorTranslator.ToHtml(c);
        }


    }
}
